<template>
  <!-- 权限分配组件：角色管理中为角色分配权限的Dialog -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <!-- 角色码（只读） -->
      <el-form-item label="角色码" prop="role">
        <el-input v-model="form.role" :disabled="true" />
      </el-form-item>
      <!-- 角色名（只读） -->
      <el-form-item label="角色名称" prop="title">
        <el-input v-model="form.title" :disabled="true" />
      </el-form-item>
      <!-- 菜单选择树 -->
      <el-form-item label="菜单">
        <div class="vab-tree-border">
          <el-input v-model="filterText" placeholder="输入关键字进行过滤" />
          <el-tree
            ref="treeRef"
            v-loading="loading"
            :check-on-click-node="true"
            :data="list"
            :default-checked-keys="checked"
            default-expand-all
            :filter-node-method="filterNode"
            node-key="id"
            :show-checkbox="true"
          >
            <template #default="{ data }">
              <span v-if="!data.disabled">{{ data.meta.title }}</span>
              <span v-else style="color: #cfd3dc">
                {{ data.meta.title }}-[禁用]
              </span>
            </template>
          </el-tree>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button style="font-size: 16px" @click="close">取 消</el-button>
      <el-button
        v-if="!saveLoading"
        style="
          background-color: #58b5e1;
          color: #fff;
          border: 0px;
          font-size: 14px;
        "
        @click="save"
      >
        确 定
      </el-button>
      <el-button v-else type="info">
        请求中
        <i class="el-icon-loading"></i>
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import {
    defineComponent,
    getCurrentInstance,
    onMounted,
    reactive,
    toRefs,
  } from 'vue'
  import { doRulesEdit } from '@/api/system_group'
  import { getList } from '@/api/router'
  import { getCheckedData } from '@/api/system_group'

  export default defineComponent({
    name: 'RoleManagementEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const { proxy } = getCurrentInstance()

      const state = reactive({
        formRef: null,
        treeRef: null,
        loading: true,
        saveLoading: false,
        filterText: '',
        checked: [],
        form: {
          btnRolesCheckedList: [],
        },
        title: '',
        dialogFormVisible: false,
        list: [],
      })
      /**
       * 打开页面
       */
      const showEdit = async (row) => {
        state.loading = true
        state.dialogFormVisible = true
        await fetchData()
        if (!row) {
          state.title = '页面异常'
        } else {
          await getChecked(row)
          state.title = '分配权限'
          state.form = Object.assign({}, row)
        }
      }
      /**
       * 关闭页面
       */
      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          btnRolesCheckedList: [],
        }
        state.checked = []
        state.list = []
        state.saveLoading = false
        state.dialogFormVisible = false
      }
      /**
       * 获取数据
       */
      const fetchData = async () => {
        const {
          data: { list },
        } = await getList()
        state.list = list
      }

      /**
       * 根据角色id，获取权限id
       * @param row
       * @returns {Promise<void>}
       */
      const getChecked = async (row) => {
        const param = {
          id: row.id,
        }
        const {
          data: { list },
        } = await getCheckedData(param)
        state.checked = list
        setTimeout(function () {
          state.loading = false
        }, 300)
      }

      /**
       *保存方法
       */
      const save = () => {
        if (state.saveLoading) return false
        state.saveLoading = true
        state['formRef'].validate(async (valid) => {
          if (valid) {
            //getCheckNodes可以获取所有父级树
            const rules = state['treeRef'].getCheckedNodes(false, true)
            let arr = []
            rules.forEach((it) => {
              arr.push(it.id)
            })
            const { msg } = await doRulesEdit({
              id: state.form.id,
              rules: arr,
            })
            state.saveLoading = false
            proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }

      onMounted(() => {
        // fetchData()
      })
      return {
        ...toRefs(state),
        showEdit,
        close,
        fetchData,
        save,
      }
    },
    watch: {
      filterText(val) {
        if (val) {
          this.$refs.treeRef.filter(val)
        } else {
          this.$refs.treeRef.filter(val)
        }
      },
    },
    methods: {
      filterNode(value, data) {
        if (!value) return true
        return data.title.indexOf(value) !== -1
      },
    },
  })
</script>

<style lang="scss" scoped>
  .vab-tree-border {
    height: 200px;
    padding: $base-padding;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: $base-border-radius;
  }
</style>
